import { useEffect } from 'react';
import './App.scss';
import { fetchDataFromApi } from './utils/api';
import { useAppDispatch, useAppSelector } from './store/hook';
import { getApiConfiguration, getGenres } from './store/modules/homeSlice';
import { HashRouter as Router, Routes, Route } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import Home from './pages/Home';
import Details from './pages/Details';
import SearchResult from './pages/SearchResult';
import Explore from './pages/Explore';
import NotFound from './pages/404';

function App() {
  const { url, genres } = useAppSelector(state => state.home);
  const dispatch = useAppDispatch();

  useEffect(() => {
    const initData = async () => {
      const data = await fetchDataFromApi('/configuration');
      const url = {
        backdrop: data.images.secure_base_url + 'original',
        poster: data.images.secure_base_url + 'original',
        profile: data.images.secure_base_url + 'original',
      };
      dispatch(getApiConfiguration(url));
    };

    initData();
    genresCall();
  }, []);

  const genresCall = async () => {
    let promises: any = [];
    let endPoints = ['tv', 'movie'];
    let allGenres: any = {};

    endPoints.forEach(url => {
      promises.push(fetchDataFromApi(`/genre/${url}/list`, { language: 'zh-CN'}));
    });

    const data = await Promise.all(promises);
    data.map(({ genres }) => {
      return genres.map((item: any) => (allGenres[item.id] = item));
    });

    dispatch(getGenres(allGenres));
  };

  return (
    <Router>
      <Header />
      <Routes>
        <Route path="/" element={<Home />}></Route>
        <Route path="/:mediaType/:id" element={<Details />} />
        <Route path="/search/:query" element={<SearchResult />} />
        <Route path="/explore/:mediaType" element={<Explore />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
      <Footer />
    </Router>
  );
}

export default App;
